# coding=utf-8
import serial
import serial.tools.list_ports
import time
from pygame import mixer
import time


def playsound(number):
    mixer.init()
    mixer.music.load('F:\\Users\\Wanchao Sang\\PycharmProjects\\netSpeed\\daizuo\\voice\\'+number+'.mp3')
    mixer.music.play()
    while mixer.music.get_busy() and ser.inWaiting()<=0:
        print("busy...")
        time.sleep(1)
    mixer.music.stop()

# 得到串口名
def finaPort_Name():
    port_list = list(serial.tools.list_ports.comports())
    if len(port_list) <= 0:
        print("The Serial port can't find!")
    else:
        portname_list = []
        for i in list(port_list):
            port_list_0 = list(i)
            port_serial = port_list_0[0]
            portname_list.append(port_serial)

        return portname_list


# 收发数据
def receive_Portdata():
    while 1:
        str = input("请输入要发送的数据（非中文）并同时接收数据: ")
        portStr = []
        ser.write((str + '\n').encode())

        while 1:
            str1 = ser.readline()
            if str1 == b'@_@':
                portStr.append(str1)
                print(str1.decode().strip())
                break
            elif str1 == b'':
                continue
            else:
                portStr.append(str1)
                print(str1.decode().strip())

                res = str1.decode().strip()
                if "0001" in res:
                    playsound('0001')
                elif "0002" in res:
                    playsound('0002')
                elif "0003" in res:
                    playsound('0003')
                elif "0004" in res:
                    playsound('0004')
                elif "0005" in res:
                    playsound('0005')
                elif "0006" in res:
                    playsound('0006')
                elif "0007" in res:
                    playsound('0007')
        ser.close()


name = finaPort_Name()
ser = serial.Serial(port=name[3], baudrate=9600, timeout=0.02)
receive_Portdata()